package com.gensdai.leliang.retrofitUtils.okhttputils;

import android.content.Context;
import android.util.Log;

import com.gensdai.leliang.BuildConfig;
import com.gensdai.leliang.retrofitUtils.cookieutils.CookieManger;
import com.readystatesoftware.chuck.ChuckInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by zsxx on 2017/6/19.
 */

public class Okhttp3Utils {

    //日志显示级别  如果需要从head头打印 请把body改成HEADERS
    public static HttpLoggingInterceptor.Level level= HttpLoggingInterceptor.Level.BODY;

    public static OkHttpClient okHttpClient;

    public static OkHttpClient getOkhttpClient(Context context){
        if(okHttpClient == null){
            //添加支持服务器从COOKIE中get set数据
            //新建log拦截器
            HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.d("lelong_retrofit_back","OkHttp====Message:"+message);
                }
            });
            //设置日志打印级别
            loggingInterceptor.setLevel(level);
            //使用cookiejar的方式做cookie的操作     有些网站的cookie有可能不支持cookiejar的方式 请注释掉cookiejar  用两个interceptor的方式试试 如果使用interceptor的方式 报错请先注释掉loggingInterceptor
            OkHttpClient.Builder okHttp = new OkHttpClient.Builder()
//                  .addInterceptor(new ReceivedCookiesInterceptor(context))
//                  .addInterceptor(new AddCookiesInterceptor(context))
                    .cookieJar(new CookieManger(context))
                    .connectTimeout(30, TimeUnit.SECONDS)   //连接超时时间，在指定时间内还没有连接到服务器就会报SocketTimeout异常
                    .readTimeout(30, TimeUnit.SECONDS)     //读取超时时间，是连接后在指定时间还没有获取到数据就超时。
                    ;

            if(BuildConfig.DEBUG){
                okHttp.addInterceptor(loggingInterceptor);
                okHttp.addInterceptor(new ChuckInterceptor(context));
            }

            okHttpClient = okHttp.build();
        }

        return okHttpClient;


    }

}
